package com.grieous.solr;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.request.CoreAdminRequest;
import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
import org.apache.solr.common.params.ModifiableSolrParams;

public class SolrServerManager {
	private static SolrServerManager solrServerManager = null;
	private static HttpSolrServer server = null;

	private static String url = "http://" + getSolrServerIpConfig() + "/solr/";

	
	public static String getUrl() {
		return url;
	}

	public static synchronized SolrServerManager getInstance() {
		if (solrServerManager == null) {
			solrServerManager = new SolrServerManager();
		}
		return solrServerManager;
	}

	public static HttpSolrServer getHttpSolrServer() {
		if (server == null) {
			server = new HttpSolrServer(url);
			server.setSoTimeout(1000); // socket read timeout
			server.setConnectionTimeout(1000);
			server.setDefaultMaxConnectionsPerHost(100);
			server.setMaxTotalConnections(100);
			server.setFollowRedirects(false); // defaults to false
			server.setAllowCompression(true);
			server.setMaxRetries(1);// defaults to 0. > 1 not recommended.
		}
		return server;
	}

	public void swapCore(String coreName, String otherCoreName) {
		try {
			HttpSolrServer server = getHttpSolrServer();
			CoreAdminRequest request = new CoreAdminRequest();
			request.setAction(CoreAdminAction.SWAP);
			request.setCoreName(coreName);
			request.setOtherCoreName(otherCoreName);
			request.process(server);
			reloadCore();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void reloadCore() {
		try {
			HttpSolrServer server = getHttpSolrServer();
			CoreAdminRequest request = new CoreAdminRequest();
			request.setAction(CoreAdminAction.RELOAD);
			request.process(server);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	
	public void createIndex(String coreName) {
		try {
			HttpSolrServer server = getHttpSolrServer();
			server.setBaseURL(url + coreName);
			ModifiableSolrParams params = new ModifiableSolrParams();
			params.set("qt", "/dataimport");
			params.set("command", "full-import");
			params.set("commit", "true");
			params.set("optimize", "true");
			params.set("clean", "true");
			server.query(params);
			server.setBaseURL(url);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getSolrServerIpConfig() {
		InputStream inputStream = SolrServerManager.class.getClassLoader()
				.getResourceAsStream("solr.properties");
		Properties p = new Properties();
		try {
			p.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return p.getProperty("solr_server");
	}

}
